package system

import (
	"gitee.com/sansaniot/ssiot-core/facade/env"
	"gitee.com/sansaniot/ssiot-core/logger"
	"gitee.com/sansaniot/ssiot-core/sdk"

	"ssdevice/common/constant"
	"ssdevice/common/enums"
	mq "ssdevice/common/middleware/mqtt"
	"ssdevice/internal/data/action"
	"ssdevice/internal/data/partition"
	"ssdevice/internal/data/thread"
	"ssdevice/internal/device/models"
	"ssdevice/internal/device/models/query"
)

func InitSystemBiz() {
	// 注册业务类
	initRegistryPartition()
	// 缓存初始化
	initSystemCache()
	// 启动数据线程
	initDataThread()
	// 启动mqtt客户端
	initMqttClient()
}

func initRegistryPartition() {
	// 获取db
	db := sdk.Runtime.GetDbByKey("db")
	if db == nil {
		return
	}
	// 登录
	loginAction := &action.Login{Orm: db}
	partition.Registry(enums.Login.Get().Name, loginAction)
	loginAction.Run("LoginThread")
	// 登出
	partition.Registry(enums.Logout.Get().Name, &action.Logout{Orm: db})
	// 属性
	partition.Registry(enums.Props.Get().Name, &action.Props{Orm: db})
	partition.Registry(enums.Sensor.Get().Name, &action.Sensor{Orm: db})
	// 配置
	partition.Registry(enums.Config.Get().Name, &action.Config{Orm: db})

}

func initDataThread() {
	// 历史数据
	thread.DevHisDataThread{}.Run("DevHisDataThread")
}

func initMqttClient() {
	mq.MqttClient = mq.NewClient()
	// 固定订阅主题
	mq.MqttClient.InitSubscribe("/iot/"+constant.TopicPlaceholder+"/+/login", mq.TopicHandler)
	mq.MqttClient.InitSubscribe("/iot/"+constant.TopicPlaceholder+"/+/logout", mq.TopicHandler)
	mq.MqttClient.InitSubscribe("/iot/"+constant.TopicPlaceholder+"/+/props", mq.TopicHandler)
	mq.MqttClient.InitSubscribe("/iot/"+constant.TopicPlaceholder+"/+/sensor", mq.TopicHandler)
	mq.MqttClient.InitSubscribe("/iot/"+constant.TopicPlaceholder+"/+/config/#", mq.TopicHandler)
	mq.MqttClient.InitSubscribe("/iot/"+constant.TopicPlaceholder+"/+/ota/#", mq.TopicHandler)
	if _, err := mq.MqttClient.CreateClient(); err != nil {
		logger.Error("mqtt连接失败" + err.Error())
	}
}

func initSystemCache() {
	// 获取db
	db := sdk.Runtime.GetDbByKey("db")
	if db == nil {
		return
	}
	// 查所有设备
	devModel := &models.SysDev{}
	devModel.Orm = db
	req := query.SysDevQuery{}
	req.UserId = "1"
	err, result := devModel.FindDeviceList(&req)
	if err != nil {
		logger.Error(err)
		return
	}
	delCaches, _ := env.Cache.HashGetAll(constant.DeviceEasyCache)
	devList := result.([]models.SysDev)
	cacheMap := map[string]interface{}{}
	for _, v := range devList {
		cacheMap[v.Sn] = v.Type
		delete(delCaches, v.Sn)
	}
	// 设备缓存与清理
	_ = env.Cache.HashSet(constant.DeviceEasyCache, cacheMap)
	for sn := range delCaches {
		_ = env.Cache.HashDel(constant.DeviceEasyCache, sn)
	}
}
